package com.hanson.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hanson.Const;
import com.hanson.common.bean.GoodsRuleItemBean;
import com.hanson.common.bean.SkillTimeBean;
import com.hanson.common.exception.BusinessException;
import com.hanson.common.util.BusinessUtil;
import com.hanson.entity.GoodsAttrBean;
import com.hanson.entity.GoodsAttrValueBean;
import com.hanson.entity.GoodsBean;
import com.hanson.entity.SeckillGoodsBean;
import com.hanson.mapper.GoodsAttrBeanMapper;
import com.hanson.mapper.GoodsAttrValueBeanMapper;
import com.hanson.mapper.SeckillGoodsBeanMapper;
import com.hanson.mapper.UserBeanMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

import java.text.ParseException;
import java.util.*;

@Slf4j
@Service
public class SeckillGoodsService {
    @Autowired
    private SeckillGoodsBeanMapper seckillGoodsBeanMapper;
    @Autowired
    private UserBeanMapper userBeanMapper;
    @Autowired
    private GoodsAttrBeanMapper goodsAttrBeanMapper;
    @Autowired
    private GoodsAttrValueBeanMapper goodsAttrValueBeanMapper;
    @Autowired
    private SmsService smsService;

    public GoodsBean getRules(int id) {
        SeckillGoodsBean returnBean = seckillGoodsBeanMapper.selectByPrimaryKey(id);
        if (null == returnBean) {
            throw new BusinessException("ID不正确");
        }
        GoodsBean goodsBean = new GoodsBean();
        goodsBean.setId(returnBean.getId());
        goodsBean.setSpecType(null == returnBean.getSpecType() ? "0" : String.valueOf(returnBean.getSpecType()));
        List<GoodsAttrBean> goodsAttrBeanList = goodsAttrBeanMapper.selectByGoodsId(id, 3);
        if (CollectionUtils.isNotEmpty(goodsAttrBeanList)) {
            List<GoodsRuleItemBean> items = new ArrayList<>();
            goodsAttrBeanList.stream().forEach(c -> {
                GoodsRuleItemBean goodsRuleItemBean = new GoodsRuleItemBean();
                goodsRuleItemBean.setValue(c.getAttrName());
                goodsRuleItemBean.setDetail(Arrays.asList(c.getAttrValues().split(",")));
                goodsRuleItemBean.setDetailValue("");
                items.add(goodsRuleItemBean);
            });
            goodsBean.setItems(items);
        } else {
            goodsBean.setItems(new ArrayList<>());
        }
        List<GoodsAttrValueBean> goodsAttrValueBeanList = goodsAttrValueBeanMapper.selectByByGoodsId(id, 3);
        if (CollectionUtils.isNotEmpty(goodsAttrValueBeanList)) {
            //单规格
            if (goodsBean.getSpecType().equals("0")) {
                goodsBean.setAttr(JSONObject.parseObject(goodsAttrValueBeanList.get(0).getDetail(), GoodsAttrValueBean.class));
                goodsBean.setAttrs(new ArrayList<>());
            } else {
                List<JSONObject> attrs = new ArrayList<>();
                goodsAttrValueBeanList.stream().forEach(c -> {
                    JSONObject jsonObject = (JSONObject) JSONObject.parse(c.getDetail());
                    jsonObject.put("suk", c.getSuk());
                    attrs.add(jsonObject);
                });
                goodsBean.setAttrs(attrs);
                goodsBean.setAttr(new GoodsAttrValueBean());
            }
        } else {
            goodsBean.setAttr(new GoodsAttrValueBean());
            goodsBean.setAttrs(new ArrayList<>());
        }
        return goodsBean;
    }

    @Transactional(rollbackFor = Exception.class)
    public void setRules(SeckillGoodsBean seckillGoodsBean) {
        SeckillGoodsBean returnBean = seckillGoodsBeanMapper.selectByPrimaryKey(seckillGoodsBean.getId());
        if (null == returnBean) {
            throw new BusinessException("ID不正确");
        }
        returnBean.setUpdateDate(new Date());
        returnBean.setSpecType(null == seckillGoodsBean.getSpecType() ? 0 : seckillGoodsBean.getSpecType());
        seckillGoodsBeanMapper.updateByPrimaryKey(returnBean);

        goodsAttrBeanMapper.deleteByGoodsId(seckillGoodsBean.getId(), 3);
        goodsAttrValueBeanMapper.deleteByGoodsId(seckillGoodsBean.getId(), 3);
        /***商品规格 但规格的为空*/
        if (CollectionUtils.isNotEmpty(seckillGoodsBean.getItems())) {
            seckillGoodsBean.getItems().stream().forEach(c -> {
                GoodsAttrBean goodsAttrBean = new GoodsAttrBean();
                goodsAttrBean.setGoodsId(seckillGoodsBean.getId());
                goodsAttrBean.setAttrName(c.getValue());
                goodsAttrBean.setAttrValues(String.join(",", c.getDetail()));
                goodsAttrBean.setGoodsType(3);
                goodsAttrBeanMapper.insert(goodsAttrBean);
            });
        }

        /**商品规格组合结果**/
        if (CollectionUtils.isNotEmpty(seckillGoodsBean.getAttrs())) {
            for (JSONObject c : seckillGoodsBean.getAttrs()) {
                GoodsAttrValueBean goodsAttrValueBean = new GoodsAttrValueBean();
                if (c.containsKey("detail")) {
                    JSONObject detailJson = c.getJSONObject("detail");
                    StringBuffer sukSb = new StringBuffer();
                    for (Map.Entry<String, Object> entry : detailJson.entrySet()) {
                        sukSb.append(entry.getValue()).append(",");
                    }
                    goodsAttrValueBean.setSuk(sukSb.substring(0, sukSb.length() - 1).toString());
                }
                Integer stockValue = c.getInteger("stock");
                stockValue = stockValue == null ? 0 : stockValue;
                goodsAttrValueBean.setDetail(JSON.toJSONString(c));
                goodsAttrValueBean.setGoodsId(seckillGoodsBean.getId());
                goodsAttrValueBean.setStock(stockValue);
                goodsAttrValueBean.setVipPrice(BusinessUtil.getDbAmount(c.getString("vipPrice")) + "");
                goodsAttrValueBean.setPrice(BusinessUtil.getDbAmount(c.getString("price")) + "");
                goodsAttrValueBean.setSpreadMoney(BusinessUtil.getDbAmount(c.getString("spreadMoney")) + "");
                goodsAttrValueBean.setSpreadChildMoney(BusinessUtil.getDbAmount(c.getString("spreadChildMoney")) + "");
                goodsAttrValueBean.setImage(c.getString("image"));
                goodsAttrValueBean.setGoodsType(3);
                goodsAttrValueBeanMapper.insert(goodsAttrValueBean);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(SeckillGoodsBean seckillGoodsBean) throws Exception {
        if (null == seckillGoodsBean.getGoodsId()) {
            throw new BusinessException("商品ID不能为空");
        }
        List<SeckillGoodsBean> seckillGoodsBeanList = seckillGoodsBeanMapper.selectByGoodsId(seckillGoodsBean.getGoodsId());
        if (CollectionUtils.isNotEmpty(seckillGoodsBeanList)) {
            throw new BusinessException("当前商品已在秒杀中，不能重复添加");
        }
        seckillGoodsBean.setCreateDate(new Date());
        seckillGoodsBean.setStatus(0);
        seckillGoodsBean.setIsShow(1);
        seckillGoodsBean.setGoodsPrice(BusinessUtil.getDbAmount(seckillGoodsBean.getWebGoodsPrice()));
        seckillGoodsBean.setSeckillPrice(BusinessUtil.getDbAmount(seckillGoodsBean.getWebSeckillPrice()));
        seckillGoodsBean.setSpecType(0);
        seckillGoodsBeanMapper.insert(seckillGoodsBean);
        //设置默认规格
        GoodsAttrValueBean goodsAttrValueBean = new GoodsAttrValueBean();
        String detailTemplate = "{\"spreadChildMoney\":\"0\",\"price\":\"%s\",\"vipPrice\":\"%s\",\"stock\":\"9999\",\"spreadMoney\":\"0\"}";
        goodsAttrValueBean.setDetail(String.format(detailTemplate, seckillGoodsBean.getWebSeckillPrice(), seckillGoodsBean.getWebSeckillPrice()));
        goodsAttrValueBean.setGoodsId(seckillGoodsBean.getId());
        goodsAttrValueBean.setStock(9999);
        goodsAttrValueBean.setVipPrice(seckillGoodsBean.getSeckillPrice() + "");
        goodsAttrValueBean.setPrice(seckillGoodsBean.getSeckillPrice() + "");
        goodsAttrValueBean.setSpreadMoney("0");
        goodsAttrValueBean.setSpreadChildMoney("0");
        goodsAttrValueBean.setGoodsType(3);
        goodsAttrValueBeanMapper.insert(goodsAttrValueBean);
        smsService.partnerGoodsNotify(userBeanMapper.getAllPartner(), seckillGoodsBean.getGoodsName(), seckillGoodsBean.getWebGoodsPrice());
    }

    public void modify(SeckillGoodsBean seckillGoodsBean) throws Exception {
        if (null == seckillGoodsBean.getGoodsId()) {
            throw new BusinessException("商品ID不能为空");
        }
        SeckillGoodsBean returnBean = seckillGoodsBeanMapper.selectByPrimaryKey(seckillGoodsBean.getId());
        if (null != returnBean) {
            List<SeckillGoodsBean> seckillGoodsBeanList = seckillGoodsBeanMapper.selectByGoodsId(seckillGoodsBean.getGoodsId());
            if (CollectionUtils.isNotEmpty(seckillGoodsBeanList) && !seckillGoodsBeanList.get(0).getGoodsId().equals(returnBean.getGoodsId())) {
                throw new BusinessException("当前商品已在秒杀中，不能重复添加");
            }
            seckillGoodsBean.setUpdateDate(new Date());
            seckillGoodsBean.setCreateDate(returnBean.getCreateDate());
            seckillGoodsBean.setIsShow(returnBean.getIsShow());
            seckillGoodsBean.setStatus(returnBean.getStatus());
            seckillGoodsBean.setGoodsPrice(BusinessUtil.getDbAmount(seckillGoodsBean.getWebGoodsPrice()));
            seckillGoodsBean.setSeckillPrice(BusinessUtil.getDbAmount(seckillGoodsBean.getWebSeckillPrice()));
            seckillGoodsBeanMapper.updateByPrimaryKey(seckillGoodsBean);
        }
    }

    public SeckillGoodsBean selectById(Integer id) {
        SeckillGoodsBean seckillGoodsBean = seckillGoodsBeanMapper.selectByPrimaryKey(id);
        if (null != seckillGoodsBean) {
            seckillGoodsBean.setWebGoodsPrice(BusinessUtil.getWebAmount(seckillGoodsBean.getGoodsPrice()));
            seckillGoodsBean.setWebSeckillPrice(BusinessUtil.getWebAmount(seckillGoodsBean.getSeckillPrice()));
        }
        return seckillGoodsBean;
    }

    public void fillAttrs(SeckillGoodsBean seckillGoodsBean) {
        if (null == seckillGoodsBean) {
            return;
        }
        List<GoodsAttrBean> goodsAttrBeanList = goodsAttrBeanMapper.selectByGoodsId(seckillGoodsBean.getId(), 3);
        if (CollectionUtils.isNotEmpty(goodsAttrBeanList)) {
            List<GoodsRuleItemBean> items = new ArrayList<>();
            goodsAttrBeanList.stream().forEach(c -> {
                GoodsRuleItemBean goodsRuleItemBean = new GoodsRuleItemBean();
                goodsRuleItemBean.setValue(c.getAttrName());
                goodsRuleItemBean.setDetail(Arrays.asList(c.getAttrValues().split(",")));
                goodsRuleItemBean.setDetailValue("");
                items.add(goodsRuleItemBean);
            });
            seckillGoodsBean.setItems(items);
        }
        List<GoodsAttrValueBean> goodsAttrValueBeanList = goodsAttrValueBeanMapper.selectByByGoodsId(seckillGoodsBean.getId(), 3);
        if (CollectionUtils.isNotEmpty(goodsAttrValueBeanList)) {
            log.info("seckillGoodsBean.getSpecType()={}", seckillGoodsBean.getSpecType());
            //单规格
            if (null == seckillGoodsBean.getSpecType() || seckillGoodsBean.getSpecType() == 0) {
                seckillGoodsBean.setAttr(JSONObject.parseObject(goodsAttrValueBeanList.get(0).getDetail(), GoodsAttrValueBean.class));
                seckillGoodsBean.setAttrs(new ArrayList<>());
            } else {
                List<JSONObject> attrs = new ArrayList<>();
                goodsAttrValueBeanList.stream().forEach(c -> {
                    JSONObject jsonObject = (JSONObject) JSONObject.parse(c.getDetail());
                    jsonObject.put("suk", c.getSuk());
                    attrs.add(jsonObject);
                });
                seckillGoodsBean.setAttrs(attrs);
                seckillGoodsBean.setAttr(new GoodsAttrValueBean());
            }
        }
    }

    public void deleteById(Integer id) {
        seckillGoodsBeanMapper.deleteByPrimaryKey(id);
    }

    public Page<SeckillGoodsBean> listSeckillGoods(Page<SeckillGoodsBean> page, SeckillGoodsBean seckillGoodsBean) {
        List<SeckillGoodsBean> list = seckillGoodsBeanMapper.listSeckillGoods(page, seckillGoodsBean);
        if (CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(c -> {
                c.setWebGoodsPrice(BusinessUtil.getWebAmount(c.getGoodsPrice()));
                c.setWebSeckillPrice(BusinessUtil.getWebAmount(c.getSeckillPrice()));
            });
        }
        return page.setRecords(list);
    }

    public void updateIsShow(int isShow, int id) {
        seckillGoodsBeanMapper.updateIsShow(isShow, id);
    }

    public long getSurplusSecond() throws ParseException {
        Map<Integer, SkillTimeBean> skillTimeMap = Const.SKILL_TIME;
        List<SkillTimeBean> list = new ArrayList<>();
        skillTimeMap.entrySet().stream().forEach(c -> {
            SkillTimeBean skillTimeBean = c.getValue();
            list.add(skillTimeBean);
        });
        String currentDay = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
        String tomorrowDay = DateFormatUtils.format(DateUtils.addDays(new Date(), 1), "yyyy-MM-dd");
        int nowTime = Integer.parseInt(DateFormatUtils.format(new Date(), "HH"));
        int firstTime = Integer.parseInt(list.get(0).getTime().split(":")[0]);
        String activeTime = null;
        for (int i = 0; i < list.size(); i++) {
            int time = Integer.parseInt(list.get(i).getTime().split(":")[0]);
            if (i == list.size() - 1) {
                if (nowTime >= time || nowTime < firstTime) {
                    if (nowTime >= time) {
                        activeTime = tomorrowDay + " " + list.get(0).getTime();
                    } else {
                        activeTime = currentDay + " " + list.get(0).getTime();
                    }
                    break;
                }
            } else {
                int nextTime = Integer.parseInt(list.get(i + 1).getTime().split(":")[0]);
                if (nowTime >= time && nowTime < nextTime) {
                    activeTime = currentDay + " " + list.get(i + 1).getTime();
                    break;
                }
            }
        }
        long diffTime = DateUtils.parseDate(activeTime, "yyyy-MM-dd HH:mm").getTime() - System.currentTimeMillis();
        return diffTime / 1000;
    }

    /**
     * 获取首页秒杀商品
     *
     * @return
     */
    public List<SeckillGoodsBean> getIndexSkillGoods() {
        ModelMap modelMap = new ModelMap();
        List<SkillTimeBean> skillTimeBeanList = getSkillTimeData(modelMap);
        for (SkillTimeBean skillTimeBean : skillTimeBeanList) {
            if (skillTimeBean.getStatus() == 1) {
                //抢购中
                return skillTimeBean.getSeckillGoodsBeanList();
            }
        }
        return null;
    }

    public List<SkillTimeBean> getSkillTimeData(ModelMap modelMap) {
        List<SeckillGoodsBean> seckillGoodsBeanList = seckillGoodsBeanMapper.selectCurrentTimeData();
        Map<Integer, List<SeckillGoodsBean>> dataMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(seckillGoodsBeanList)) {
            seckillGoodsBeanList.stream().forEach(c -> {
                c.setWebGoodsPrice(BusinessUtil.getWebAmount(c.getGoodsPrice()));
                c.setWebSeckillPrice(BusinessUtil.getWebAmount(c.getSeckillPrice()));
                c.setUsableNum(c.getStock() - c.getSales());
                c.setPercent(BusinessUtil.getPercent(c.getStock() - c.getSales(), c.getStock()));
                if (dataMap.containsKey(c.getTimeType())) {
                    dataMap.get(c.getTimeType()).add(c);
                } else {
                    List<SeckillGoodsBean> list = new ArrayList<>();
                    list.add(c);
                    dataMap.put(c.getTimeType(), list);
                }
            });
        }

        Map<Integer, SkillTimeBean> skillTimeMap = Const.SKILL_TIME;
        List<SkillTimeBean> list = new ArrayList<>();
        skillTimeMap.entrySet().stream().forEach(c -> {
            SkillTimeBean skillTimeBean = c.getValue();
            skillTimeBean.getSeckillGoodsBeanList().clear();
            ;
            list.add(skillTimeBean);
        });
        int nowTime = Integer.parseInt(DateFormatUtils.format(new Date(), "HH"));
        int firstTime = Integer.parseInt(list.get(0).getTime().split(":")[0]);
        for (int i = 0; i < list.size(); i++) {
            int time = Integer.parseInt(list.get(i).getTime().split(":")[0]);
            if (i == list.size() - 1) {
                if (nowTime < time && nowTime > firstTime) {
                    list.get(i).setStatus(0);
                    list.get(i).setStatusName("即将开始");
                } else if (nowTime >= time || nowTime < firstTime) {
                    list.get(i).setStatus(1);
                    list.get(i).setStatusName("抢购中");
                    modelMap.put("currentIndex", i);
                } else if (nowTime >= firstTime && nowTime < time) {
                    list.get(i).setStatus(2);
                    list.get(i).setStatusName("已结束");
                }
            } else {
                int nextTime = Integer.parseInt(list.get(i + 1).getTime().split(":")[0]);
                if (nowTime >= time && nowTime < nextTime) {
                    list.get(i).setStatus(1);
                    list.get(i).setStatusName("抢购中");
                    modelMap.put("currentIndex", i);
                } else if (nowTime < time) {
                    list.get(i).setStatus(0);
                    list.get(i).setStatusName("即将开始");
                } else if (nowTime >= nextTime) {
                    list.get(i).setStatus(2);
                    list.get(i).setStatusName("已结束");
                }
            }
            if (dataMap.containsKey(list.get(i).getId())) {
                list.get(i).getSeckillGoodsBeanList().addAll(dataMap.get(list.get(i).getId()));
            }
        }
        return list;
    }


}
